package com.school.hjt.schoolclasscard.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.opencvlib.ObjectDetector;
import com.school.hjt.schoolclasscard.R;
import com.school.hjt.schoolclasscard.db.CardDao;
import com.school.hjt.schoolclasscard.db.CardStudent;
import com.school.hjt.schoolclasscard.db.Cardnumber;
import com.school.hjt.schoolclasscard.db.StudentSign;
import com.school.hjt.schoolclasscard.utlis.APPUtlis;
import com.school.hjt.schoolclasscard.utlis.CameraManager;
import com.school.hjt.schoolclasscard.utlis.ClassCalendar;
import com.school.hjt.schoolclasscard.utlis.Constant;
import com.school.hjt.schoolclasscard.utlis.DialogUtlis;
import com.school.hjt.schoolclasscard.utlis.PrefUtild;

import org.opencv.core.Scalar;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FaceTrackingActivity extends Activity {
    private ArrayList<ObjectDetector> mObjectDetects;
    private ObjectDetector mFaceDetector;
    private float absoluteFaceSize = 2.2F;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private CameraManager cameraManager;
    private CardView cv_face;
    private int i=15;
    private StudentReceiver newsReceiver;
    EditText tv_Card;
    private boolean is=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getSupportActionBar().hide();
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);
        setContentView(R.layout.activity_face_tracking);
        newsReceiver = new StudentReceiver();
        registerReceiver(newsReceiver, filter());
        tv_Card= (EditText) findViewById(R.id.tv_Card);
        cv_face=findViewById(R.id.cv_face);
        mObjectDetects = new ArrayList<>();
        mFaceDetector = new ObjectDetector(this, R.raw.haarcascade_frontalface_alt, 6, absoluteFaceSize, absoluteFaceSize, new Scalar(255, 0, 0, 255));
        mObjectDetects.add(mFaceDetector);
        mSurfaceView = (SurfaceView) findViewById(R.id.java_surface_view);
        mSurfaceHolder = mSurfaceView.getHolder();

        // mSurfaceView 不需要自己的缓冲区
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // mSurfaceView添加回调
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) { //SurfaceView创建
                try {
                    cameraManager = new CameraManager(FaceTrackingActivity.this, mObjectDetects , mSurfaceHolder);
                    cameraManager.openDriver();
                    cameraManager.startPreview();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) { //SurfaceView销毁
                holder.removeCallback(this); // Camera is being used after Camera.release() was called
                cameraManager.stopPreview();
                cameraManager.closeDriver();
            }
        });
        handler.postDelayed(runnable1, 11000);
        initIdNumber();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (; i >0; i--) {
                    handler1.sendEmptyMessage(1);
                    if(i<=0){
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                handler1.sendEmptyMessage(2);
            }
        }).start();
    }
    Handler handler1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
//                tv_countdown.setText("还剩" + i + "关闭界面");
            } else {
                is=false;
//                DialogUtlis.DialogCloose();
                finish();
            }
        }
    };
    Handler handler=new Handler();
    Runnable runnable1=new Runnable(){
        @Override
        public void run() {
            isFace="";
        }
    };

    private String isFace=Constant.cardStudent.getCard_no();
    private void initIdNumber() {
        tv_Card.requestFocus();
        tv_Card.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String strCardNo=tv_Card.getText().toString().trim();
                if (!isFace.equals(strCardNo)&&is){
                    i=18;
                    isFace=strCardNo;
                    setCard(strCardNo);
                    handler.removeCallbacks(runnable1);
                    handler.postDelayed(runnable1, 11000);
                }
                tv_Card.setText("");
                return false;
            }
        });
    }
    /**
     * @param strCardNo 卡号
     *   打卡
     */
    public void setCard(String strCardNo){
        List<Cardnumber> card = CardDao.queryLove(strCardNo);
        for (int i=0;i<card.size();i++){
           if(card.get(i).getType()==1) {
               is=false;
               LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) cv_face.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
               linearParams.width =780;// 控件的宽强制设成30
               linearParams.height=575;
               cv_face.setLayoutParams(linearParams);
//               mSurfaceView.setVisibility(View.VISIBLE);
               cameraManager.startPreview1();
//               DialogUtlis.DialogCloose();
               Constant.cardStudent=card.get(i).getCardStudent();

//               tv_student.setText("");
            }
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(newsReceiver);
        cameraManager.stopPreview();
        cameraManager.closeDriver();
    }
    /**
     * 广播类
     */
    private class StudentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case "Student":
                        Log.e("ATG","进来人脸");
                        LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) cv_face.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
                        linearParams.width = 1;// 控件的宽强制设成30
                        linearParams.height=1;
                        cv_face.setLayoutParams(linearParams);
                        DialogUtlis.showStudentDialog(FaceTrackingActivity.this,Constant.cardStudent.getStudent_url());
                        setTimecard(3);
                        new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            is=true;
                        }
                        },1000);
                    break;
            }
        }
    }
    public void setTimecard(int code){
        setSign(Constant.cardStudent,code);
    }
    public void setSign(CardStudent cardStudent, int type){
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
//        StudentSign(cardStudent.id, ClassCalendar.getStringMinuts(), type, ClassCalendar.getCardtime(), cardStudent.card_no,"")
        StudentSign sign = new  StudentSign(cardStudent.getId(),ClassCalendar.getStringMinuts(), ClassCalendar.getCardtime(), type, str, cardStudent.getCard_no(),cardStudent.getStudent_url());
        CardDao.insertSign(sign);
        Intent intent=new Intent();
        intent.setAction(Constant.KQ);
        sendBroadcast(intent);
    }
    /**
     * @return IntentFilter 广播
     */
    private IntentFilter filter(){
        IntentFilter filter = new IntentFilter();
        filter.addAction("Student");//
        return filter;
    }
}